<template>
  <div class="pop-up">
    <el-form ref="form" :model="form" label-width="1.2rem">
      <el-row>
        <!-- <el-col :span="7">
          <el-form-item label="间隔单元:">
            <el-select v-model="form.name2" placeholder="请选择">
              <el-option
              <el-option
                v-for="item in jgdyOptions"
                :key="item.intervalId"
                :label="item.intervalName"
                :value="item.intervalId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>-->
        <el-col :span="15">
          <el-form-item label="监测时间:">
            <el-date-picker
              v-model="form.name"
              type="daterange"
              align="right"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd HH:mm:ss"
              style="width:100%"
              :picker-options="pickerOptions"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="3" :offset="1">
          <el-button class="btn" type="primary" icon="el-icon-search" @click="initsearch">搜索</el-button>
        </el-col>
        <el-col :span="3">
          <el-button class="btn btn2" type="primary" v-if="ishoowHxdb" @click="hxdbClick">横向对比</el-button>
          <el-button class="btn btn2" type="primary" v-if="!ishoowHxdb" @click="hxdbClick">返回</el-button>
        </el-col>
      </el-row>
    </el-form>
    <div class="foot" v-if="ishoowHxdb">
      <div>
        <div
          class="InternetThings-con"
          v-loading="loading"
          element-loading-text="数据加载中"
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(0, 0, 0, 0.8)"
        >
          <el-table
            :data="tableData"
            :row-class-name="tableRowClassName"
            style="width: 100%"
            border
            height="100%"
          >
            <!-- <el-table-column prop="intervalName" label="间隔" :show-overflow-tooltip="true"></el-table-column> -->
            <!-- <el-table-column prop="name" label="名称" :show-overflow-tooltip="true"></el-table-column> -->
            <!-- <el-table-column prop="monitorType" :show-overflow-tooltip="true" label="监测类型"></el-table-column> -->
            <el-table-column
              prop="monitorTime"
              :show-overflow-tooltip="true"
              width="160"
              label="监测时间"
            ></el-table-column>
            <el-table-column prop="value" label="监测值" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column prop="state" :show-overflow-tooltip="true" label="状态">
              <template slot-scope="scope">
                <div
                  :class="scope.row.state | collectionValueFilter"
                >{{ scope.row.state | zxjcState}}</div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div class="echa-box">
        <div class="blueTitleStyle">{{this.typeNameTitle || ""}}</div>
        <div
          class="echaLoading"
          v-loading="loading2"
          element-loading-text="数据加载中"
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(0, 0, 0, 0.8)"
        >
          <Nodata v-if="nodata2" />
          <v-chart v-if="!nodata2" :options="option" :auto-resize="true" @click="chartClick" />
        </div>
      </div>
      <div class="pagination elPaginationStyle">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pages.page"
          :page-sizes="[5, 10, 15]"
          :page-size="pages.pageSize"
          layout="total,prev, pager, next,sizes, jumper"
          :total="pages.totalSize"
        ></el-pagination>
      </div>
    </div>
    <div class="foot2" v-if="!ishoowHxdb">
      <div>
        <el-tree
          ref="taskT"
          :data="TreeDataByType"
          show-checkbox
          :props="defaultProps"
          @check-change="handleNodeClick"
          :filter-node-method="filterNode"
          icon-class="custom"
        ></el-tree>
      </div>
      <div>
        <Nodata v-if="nodata3" />
        <v-chart v-if="!nodata3" :options="newOption2" :auto-resize="true" />
      </div>
    </div>
  </div>
</template>
<script lang="ts">
import { Component, Vue, Prop, Watch } from "vue-property-decorator";
import { EChartOption } from "echarts";
import time from "@/utils/time.js";
import lodash from "lodash";
import Nodata from "@/components/Nodata/index.vue";
import { log } from "three";
@Component({
  components: { Nodata },
})
export default class extends Vue {
  public pickerOptions: any = {
    shortcuts: [
      {
        text: "本日",
        onClick(picker) {
          var now = new Date().getTime();
          var startTime = now - 3600 * 1000 * 24 * 1;
          console.log(new Date(startTime), new Date(now));
          picker.$emit("pick", [new Date(startTime), new Date(now)]);
        },
      },
      {
        text: "本周",
        onClick(picker) {
          const weekEnd = new Date().getTime();
          // const weekStart = (new Date().getDate(), 0);
          const weekStart = weekEnd - 3600 * 1000 * 24 * 7;
          picker.$emit("pick", [new Date(weekStart), new Date(weekEnd)]);
        },
      },
      {
        text: "本月",
        onClick(picker) {
          const monthEnd = new Date().getTime();
          // const monthStart = new Date().getMonth() - 1;
          const monthStart = monthEnd - 3600 * 1000 * 24 * 30;
          picker.$emit("pick", [new Date(monthStart), new Date(monthEnd)]);
        },
      },
    ],
  };
  @Prop() obj!: any;
  // tree数据
  @Prop({ default: () => [] })
  equipments;
  @Prop({ default: () => [] })
  table03Arr;
  //横向对比 切换
  ishoowHxdb = true;
  get nodata() {
    let nodata = false;
    if (this.tableData.length === 0 && !this.loading) {
      nodata = true;
    }
    return nodata;
  }
  get nodata2() {
    let nodata = false;
    if (this.option.xAxis.data.length === 0 && !this.loading2) {
      nodata = true;
    }
    return nodata;
  }
  get nodata3() {
    // let nodata = false;
    // if (this.option.xAxis.data.length === 0 && !this.loading2) {
    //   nodata = true;
    // }
    return false;
  }
  //弹框from表单
  form = {
    name2: "",
    name: [],
  };
  //分页数据事件相关
  pages = {
    pageSize: 10,
    page: 1,
    totalSize: 0,
  };
  jgdyOptions = [];
  //树图数据
  treedata = [];
  public defaultProps = {
    label: "name",
    children: "children",
  };
  public datatime: any = "";
  public datatime7: any = "";
  typeNameTitle: string = "11";
  //表格数据
  tableData = [];
  //table数据状态
  loading = false;
  //图表数据状态
  loading2 = false;
  public option: any = {
    color: ["#2CACFB"],
    grid: {
      left: "5%",
      top: "10%",
      right: "6%",
      bottom: "6%",
      containLabel: true,
    },
    tooltip: {
      show: true,
      trigger: "axis",
    },
    dataZoom: [
      {
        type: "slider",
        show: true,
        height: 20,
        right: "10%",
        left: "10%",
        bottom: "2%",
        start: 0,
        // end: 100,
        textStyle: {
          color: "#d4ffff",
          fontSize: 11,
        },
      },
      {
        type: "inside",
      },
    ],
    xAxis: {
      type: "category",
      boundaryGap: false,
      axisLabel: {
        color: "#fff",
        // interval: 0,
        rotate: 60,
      },
      axisTick: {
        show: false,
      },
      axisLine: {
        lineStyle: {
          color: "#0b4ca9",
        },
      },
      data: [],
    },
    yAxis: {
      type: "value",
      axisLabel: {
        color: "#fff",
      },
      axisTick: {
        show: false,
      },
      axisLine: {
        show: false,
        lineStyle: {
          color: "#466BC2",
        },
      },
      splitLine: {
        lineStyle: {
          type: "solid",
          color: "rgba(17,24,45,1)",
        },
      },
    },
    series: [
      {
        data: [],
        type: "line",
        areaStyle: {
          color: {
            type: "linear",
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: "rgba(34, 107, 229, 1)", // 0% 处的颜色
              },
              {
                offset: 1,
                color: "rgba(34, 107, 229, 0)", // 100% 处的颜色
              },
            ],
            global: false, // 缺省为 false
          },
        },
      },
    ],
  };
  newOption2 = {};
  public option2: any = {
    color: [],
    grid: {
      left: "20",
      top: "20",
      right: "20",
      bottom: "50",
      containLabel: true,
    },
    tooltip: {
      show: true,
      trigger: "axis",
    },
    dataZoom: [
      {
        type: "slider",
        show: true,
        height: 20,
        right: "10%",
        left: "10%",
        bottom: "2%",
        start: 0,
        textStyle: {
          color: "#d4ffff",
          fontSize: 11,
        },
      },
      {
        type: "inside",
      },
    ],
    xAxis: {
      type: "category",
      boundaryGap: false,
      axisLabel: {
        color: "#fff",
        // interval: 0,
        rotate: 60,
      },
      axisTick: {
        show: false,
      },
      axisLine: {
        lineStyle: {
          color: "#0b4ca9",
        },
      },
      data: [],
    },
    yAxis: {
      type: "value",
      axisLabel: {
        color: "#fff",
      },
      axisTick: {
        show: false,
      },
      axisLine: {
        show: false,
        lineStyle: {
          color: "#466BC2",
        },
      },
      splitLine: {
        lineStyle: {
          type: "solid",
          color: "rgba(17,24,45,1)",
        },
      },
    },
    series: [],
  };
  strToColor() {
    let r = Math.round(Math.random() * 255);
    let g = Math.round(Math.random() * 255);
    let b = Math.round(Math.random() * 255);
    return `rgba(${r},${g},${b},1)`;
  }
  public chartClick(val: Object): void {
    // console.log(val);
  }
  // 表格隔行变色
  tableRowClassName({ row, rowIndex }: any): string {
    // console.log(row, rowIndex);
    if (rowIndex % 2 === 0) {
      return "row1";
    } else {
      return "row2";
    }
  }
  //   分页
  handleSizeChange(val: any) {
    // console.log(`每页 ${val} 条`);
    this.pages.pageSize = val;
    this.init();
  }
  // 分页事件
  handleCurrentChange(val: any) {
    this.$emit("setPageIndex", val);
    this.pages.page = val;
    this.init();
  }
  addType(arrData) {
    let type = "self";
    let time =
      new Date(arrData.endTime).getTime() -
      new Date(arrData.startTime).getTime();
    if (time >= 1 * 1000 * 60 * 60 * 24 && time < 2 * 1000 * 60 * 60 * 24) {
      type = "day";
    } else if (
      time >= 7 * 1000 * 60 * 60 * 24 &&
      time < 8 * 1000 * 60 * 60 * 24
    ) {
      type = "week";
    } else if (
      time >= 30 * 1000 * 60 * 60 * 24 &&
      time < 31 * 1000 * 60 * 60 * 24
    ) {
      type = "month";
    }
    return type;
  }
  // 原来的
  // addType() {
  //   let type = "self";
  //   let time =
  //     new Date(this.dataTime).getTime() - new Date(this.dataTime7).getTime();
  //   // console.log(time === 1 * 1000 * 60 * 60 * 24);
  //   // console.log(time === 7 * 1000 * 60 * 60 * 24);
  //   // console.log(time === 30 * 1000 * 60 * 60 * 24);
  //   // console.log(time);
  //   if (time === 1 * 1000 * 60 * 60 * 24) {
  //     type = "day";
  //   } else if (time === 7 * 1000 * 60 * 60 * 24) {
  //     type = "week";
  //   } else if (time === 30 * 1000 * 60 * 60 * 24) {
  //     type = "month";
  //   }
  //   return type;
  // }
  initsearch() {
    if (this.ishoowHxdb) {
      this.pages.page = 1;
      this.init();
      this.echaInit();
    } else {
      console.log(this.form.name);
      var fromEcha: any = {
        endTime: this.datatime,
        startTime: this.datatime7,
      };
      fromEcha.dwIds = this.paramsOBJ.join(",");
      fromEcha.dwMcs = this.paramsname.join(",");
      // console.log(fromEcha);

      if (this.form.name && this.form.name.length > 1) {
        fromEcha.endTime = this.form.name[1];
        fromEcha.startTime = this.form.name[0];
        if (this.form.name[1]) {
          fromEcha.endTime = this.form.name[1].slice(0, 10) + " 23:59:59";
        } else {
          fromEcha.endTime = this.form.name[1].slice(0, 10);
        }
      } else {
        fromEcha.endTime = "";
        fromEcha.startTime = "";
      }
      this.HxdbEchaInit(fromEcha);
    }
  }
  HxdbEchaInit(fromEcha) {
    (this as any).$services
      .queryHistoryCharts({ data: fromEcha })
      .then((result: any) => {
        if (result.data) {
          let option2 = lodash.cloneDeep(this.option2);
          option2.color = [];
          option2.series = [];
          option2.xAxis.data = result.data.xAxis;
          var datas = JSON.parse(JSON.stringify(result.data));
          this.$delete(datas, "xAxis");
          Object.keys(datas).forEach((key, i) => {
            option2.color.push(this.strToColor());
            option2.series.push({
              name: key,
              connectNulls: true,
              data: datas[key],
              type: "line",
            });
            console.log(key, datas[key]);
          });
          // console.log(this.option2);
          this.newOption2 = option2;
        }
        console.log(result);
      })
      .catch((err: object) => {
        console.log(err);
      });
  }
  init() {
    this.loading = true;
    var from = {
      endTime: (this as any).datatime,
      intervalId: this.form.name2,
      pageNo: this.pages.page,
      pageSize: this.pages.pageSize,
      dwId: this.obj.id,
      startTime: (this as any).datatime7,
      interval: "",
    };

    if (this.form.name && this.form.name.length > 1) {
      from.endTime = this.form.name[1];
      from.startTime = this.form.name[0];
      if (this.form.name[1]) {
        from.endTime = this.form.name[1].slice(0, 10) + " 23:59:59";
      } else {
        from.endTime = this.form.name[1].slice(0, 10);
      }
    } else {
      from.endTime = "";
      from.startTime = "";
    }
    from.interval = this.addType(from);
    (this as any).$services
      .list({ data: from })
      .then((result: any) => {
        if (result.data.records && result.data.records.length > 0) {
          var Fixed2 = result.data.records;
          // if (Fixed2 && Fixed2.length > 0) {
          //   Fixed2.map((v) => {
          //     if (v.value && v.value.length > 2) {
          //       v.value = (v.value - 0).toFixed(2) + "";
          //       var a = v.value.substring(v.value.length - 2);
          //       // console.log(a,v.value);
          //       if (a == 0) {
          //         v.value = v.value.substring(0, v.value.length - 3);
          //       }
          //     }
          //   });
          // }
        }
        // console.log(Fixed2);
        
        // this.tableData = result.data.records;
        this.tableData = Fixed2;
        this.pages.totalSize = result.data.total;
        // console.log(result);
        this.loading = false;
      })
      .catch((err: object) => {
        console.log(err);
        this.loading = false;
      });
  }
  echaInit() {
    this.loading2 = true;
    var fromEcha = {
      endTime: (this as any).datatime,
      startTime: (this as any).datatime7,
      dwId: this.obj.id,
      stationId: this.obj.stationId,
      interval: "",
    };
    if (this.form.name && this.form.name.length > 1) {
      fromEcha.endTime = this.form.name[1];
      fromEcha.startTime = this.form.name[0];
      if (this.form.name[0] == this.form.name[1]) {
        if (this.form.name[1]) {
          fromEcha.endTime = this.form.name[1].slice(0, 10) + " 23:59:59";
        } else {
          fromEcha.endTime = this.form.name[1].slice(0, 10);
        }
      }
    } else {
      fromEcha.endTime = "";
      fromEcha.startTime = "";
    }
    fromEcha.interval = this.addType(fromEcha);
    (this as any).$services
      .queryHistoryChart({ data: fromEcha })
      .then((result: any) => {
        console.log(result);
        var dataName = [];
        var dataVal = [];
        let resdata = result.data.reverse();
        result.data.map((item) => {
          dataName.push(item.time);
          dataVal.push(item.val);
        });
        this.option.xAxis.data = dataName;
        this.option.series[0].data = dataVal;
        this.loading2 = false;
      })
      .catch((err: object) => {
        console.log(err);
        this.loading2 = false;
      });
  }
  dropDown() {
    var from = {
      deviceCode: this.obj.sbValue,
      stationId: this.obj.stationId,
    };
    (this as any).$services
      .queryInterval({ data: from })
      .then((result: any) => {
        this.jgdyOptions = result.data;
      })
      .catch((err: object) => {
        console.log(err);
      });
  }
  hxdbClick() {
    this.ishoowHxdb = !this.ishoowHxdb;
  }
  paramsOBJ = []; //树图选中的id
  paramsname = []; //树图选中的name
  // 节点点击事件
  handleNodeClick(data: any) {
    let res = (this as any).$refs.taskT.getCheckedNodes();
    let paramsOBJ = [];
    let paramsname = [];
    this.paramsOBJ = res || [];
    res.forEach((v) => {
      if (v.myType === "dw") {
        paramsOBJ.push(v.id);
        paramsname.push(v.name);
      }
    });
    this.paramsname = paramsname;
    this.paramsOBJ = paramsOBJ;
  }
  // 取树图底层id
  // quTreeID(vla) {
  //   var list: any = [];
  //   vla = vla || [];
  //   console.log(vla);
  //   vla.map((item) => {
  //     if (!item.children) {
  //       list.push(item.id);
  //       this.paramsname.push(item.name);
  //     }
  //   });
  //   list = list.join(",");
  //   this.paramsname = this.paramsname.join(",");

  //   return list;
  // }
  filterNode(value: string, data: { name: string }) {
    if (!value) return true;
    return data.name.indexOf(value) !== -1;
  }
  mounted() {
    //当前时间
    var dataTime = new Date().getTime();
    (this as any).datatime = time(dataTime);
    var dataTime7 = dataTime - 3600 * 1000 * 24 * 1;
    (this as any).datatime7 = time(dataTime7);
    this.form.name.push((this as any).datatime7);
    this.form.name.push((this as any).datatime);
    this.init();
    this.echaInit();
    this.dropDown();
    this.typeNameTitle = this.obj.typeName;
    this.treedata = this.equipments;
  }
  // 根据点击的点位类型过滤树图数据
  get TreeDataByType() {
    let treedata = lodash.cloneDeep(this.treedata);
    let obj = this.obj || {};
    let type = obj.type || "";
    treedata = treedata.filter((item) => {
      if (item.children && item.children.length) {
        item.children = item.children.filter((v) => {
          return v.type === type;
        });
      }
      return item.children && item.children;
    });
    console.log(treedata);

    return treedata;
  }
  // 监听tree数据
  // @Watch("equipments", { deep: true, immediate: true })
  // private setequipments(to, fo) {
  //   this.treedata = to;
  //   console.log(to);
  // }
}
</script>

<style lang="scss" scoped>
.pop-up {
  //弹框样式
  width: 100%;
  height: 100%;
  .el-form {
    height: 0.6rem;
  }

  .btn {
    margin: 0.02rem 0 0 0.4rem;
    width: 0.84rem;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .btn2 {
    width: 1.05rem;
  }
  .foot {
    width: 100%;
    height: calc(100% - 0.6rem);
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    > div {
      width: 49%;
      height: calc(100% - 0.48rem);
    }
    // > div:nth-child(1) {
    // }
    > div:nth-child(2) {
      .echarts {
        height: calc(100% - 0.27rem);
        width: 100%;
      }
    }
    > div:nth-child(3) {
      height: 40px;
      width: 100%;
    }
    .normal {
      color: rgba(3, 204, 150, 1);
    }
    .abnormal {
      color: rgba(246, 91, 55, 1);
    }
  }
  .foot2 {
    width: 100%;
    height: calc(100% - 0.6rem);
    display: flex;
    justify-content: space-between;
    > div:nth-child(1) {
      width: 3.8rem;
      height: 100%;
      overflow-y: auto;
    }
    > div:nth-child(2) {
      width: calc(100% - 4rem);
      height: 100%;
      .echarts {
        height: calc(100% - 0.27rem);
        width: 100%;
      }
    }
  }
  .pagination {
    width: 100%;
    height: 0.5rem;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .InternetThings-con {
    width: 100%;
    height: 100%;
  }
  .echaLoading {
    width: 100%;
    height: 100%;
  }
}
</style>
<style lang="scss">
.pop-up {
  .el-form-item__label {
    font-size: 0.18rem;
  }
  .btn {
    font-size: 0.18rem;
  }
  .echa-box {
    .el-loading-mask {
      height: calc(100% - 0.27rem);
    }
  }
}
</style>
